package recursion;

/**
 * Created by IntelliJ IDEA.
 * User: 杰哥
 * Date: 2020/4/1
 * Time: 12:29
 */
public class MiGong {

    public static void main(String[] args) {
        //创建一个二维数组。模拟迷宫
        //地图
        int[][] map = new int[8][7];
        //使用1表示强，把最外一圈设置为强
        for (int i= 0; i < 7; i++ ){
            map[0][i] = 1;
            map[7][i] = 1;
        }
        for (int i= 1; i <=6; i++ ){
            map[i][0] = 1;
            map[i][6] = 1;
        }
        map[3][1] = 1;
        map[3][2] = 1;

        //输出地图
        System.out.println("地图情况");
        for (int[] items: map) {
            for (int item : items) {
                System.out.print(item+" ");
            }
            System.out.println();
        }

        System.out.println("----------------");
        //找路
        setWay(map, 1, 1);

        for (int[] items: map) {
            for (int item : items) {
                System.out.print(item+" ");
            }
            System.out.println();
        }


    }

    //使用递归回溯来给小球找路
    public static boolean setWay(int[][] map, int y, int x) {
        if(map[6][5] == 2) { //用map[6][5]表示终点
            return true;
        }else {
            if(map[y][x] == 0) {
                map[y][x] = 2;
                if(setWay(map, y+1, x)) { //向下
                    return true;
                }else if(setWay(map, y, x+1)) { //向右
                    return true;
                }else if(setWay(map, y-1, x)) { //向上
                    return true;
                }else if(setWay(map, y, x-1)) { //向左
                    return true;
                }else {
                    map[y][x] = 3;
                    return false;
                }
            }else {
                return false;
            }
        }
    }

}
